package com.chinawayltd.ews.sample.web.task;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.chinawayltd.ews.sample.core.exception.BusinessException;
import com.chinawayltd.ews.sample.manager.openApi.CustomOpenApiManager;
import com.chinawayltd.ews.sample.manager.openApi.OpenApiManager;
import com.chinawayltd.ews.sample.model.TDriver;
import com.chinawayltd.ews.sample.model.TLog;
import com.chinawayltd.ews.sample.model.TMateriel;
import com.chinawayltd.ews.sample.model.TTask;
import com.chinawayltd.ews.sample.model.openApi.TaskPushDTO;
import com.chinawayltd.ews.sample.model.openApi.VehicleHistoryDTO;
import com.chinawayltd.ews.sample.model.order.OrderDetailVO;
import com.chinawayltd.ews.sample.model.order.OrderVO;
import com.chinawayltd.ews.sample.model.task.TaskBranchVO;
import com.chinawayltd.ews.sample.model.task.TaskDetailVO;
import com.chinawayltd.ews.sample.model.task.TaskEventVO;
import com.chinawayltd.ews.sample.model.task.TaskListVO;
import com.chinawayltd.ews.sample.model.task.TaskMaterielVO;
import com.chinawayltd.ews.sample.model.task.TaskNodeVO;
import com.chinawayltd.ews.sample.model.task.TaskOrderDetailVO;
import com.chinawayltd.ews.sample.model.task.TaskStockVO;
import com.chinawayltd.ews.sample.model.task.TaskVO;
import com.chinawayltd.ews.sample.service.algorithm.DriverService;
import com.chinawayltd.ews.sample.service.common.CommonService;
import com.chinawayltd.ews.sample.service.order.OrderService;
import com.chinawayltd.ews.sample.service.task.TaskEventService;
import com.chinawayltd.ews.sample.service.task.TaskNodeService;
import com.chinawayltd.ews.sample.service.task.TaskService;
import com.chinawayltd.ews.sample.util.BaseController;
import com.chinawayltd.ews.sample.util.ResultModel;
import com.chinawayltd.ews.sample.util.StringUtils;
import com.chinawayltd.ews.sample.util.excel.ExcelGenerateModel;
import com.chinawayltd.ews.sample.util.excel.ExcelUtils;
import com.chinawayltd.ews.sample.web.query.LogGirdQuery;
import com.chinawayltd.ews.sample.web.query.OrderDetailGirdQuery;
import com.chinawayltd.ews.sample.web.query.TaskGirdQuery;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * @program: greeProject
 * @description 运输任务管理
 * @author: chenxin
 * @create: 2018年4月17日 下午7:41:00
 */
@Api(tags = { "运输任务管理API" })
@RestController
@RequestMapping(value = "/web/task")
public class TaskController extends BaseController{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private TaskService taskService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private TaskEventService taskEventService;
    @Autowired
    private TaskNodeService taskNodeService;
    @Autowired
    private DriverService driverService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private CustomOpenApiManager customOpenApiManager;
    @Autowired
    private OpenApiManager openApiManager;
    
    private static final SimpleDateFormat YYYYMMDDHHMMSS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    private final String tableName = "T_TASK";
	@Value("${sys.find.task.node.indexUrl}")
	private String findTaskIndexUrl;
	@Value("${sys.find.task.node.detailUrl}")
	private String findTaskDetailUrl;
	
    @ApiOperation(value = "运输任务信息列表查询接口")
    @RequestMapping(value = "/loadGirdData", method = { RequestMethod.POST })
    public ResultModel loadGirdData(TaskGirdQuery queryParam) {
        ResultModel model = new ResultModel();
        try {
            List<TaskListVO> list = taskService.listTaskAndOrderByPage(queryParam);
            model.setCode(0);
            model.setSub_code(0);
            model.setData(new JSONObject().fluentPut("result", list));
            model.setPage(queryParam);
        }catch (Exception e){
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("result", null));
			logger.error("运输任务列表查询出错！", e);
		}
        return model;
    }

    @ApiOperation(value = "备货指引管理列表查询接口")
    @RequestMapping(value = "/task/loadGirdData", method = { RequestMethod.POST })
    public ResultModel loadGirdData2(TaskGirdQuery queryParam) {
        ResultModel model = new ResultModel();
        try {
        	// 需要处理时间段条件taskTime
            List<TaskStockVO> list = taskService.listTaskAndOrderDetailByPage(queryParam);
            model.setCode(0);
            model.setSub_code(0);
            model.setData(new JSONObject().fluentPut("result", list));
            model.setPage(queryParam);
        }catch (Exception e){
        	model.setSub_code(1);
       	 	model.setData(new JSONObject().fluentPut("result", null));
            logger.error("备货指引管理列表查询接口！", e);
        }
        return model;
    }
    
	@ApiOperation(value = "添加任务页面的运输货物添加接口",notes="查询除去已在列表的物料的物料列表")
	@RequestMapping(value = "/getMaterielNoIds/{ids}", method = { RequestMethod.GET })
	@ApiImplicitParam(paramType = "path", name = "ids", value = "拼接需要过滤的物料数据id串如：1,2,3", dataType = "String")
	public ResultModel getMaterielNoIds(@PathVariable String ids) {
		ResultModel model = new ResultModel();
		try {
			List<TMateriel> list = taskService.listMaterielNoIds(ids);
			model.setData(new JSONObject().fluentPut("result", list));
		} catch (Exception e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("result", null));
            logger.error("添加任务页面的运输货物添加接口！", e);
		}
		return model;
	}
	
    @ApiOperation(value = "根据ID查询单个运输任务信息")
    @RequestMapping(value = "/find/{id}", method = { RequestMethod.GET })
    @ApiImplicitParam(paramType = "path", name = "id", value = "运输任务ID", dataType = "Long", required = true)
    public ResultModel getTaskById(@PathVariable Long id) {
    	ResultModel model = new ResultModel();
		try {
			TTask data = taskService.getTaskById(id);
			model.setData(new JSONObject().fluentPut("result" , data));
        }catch (Exception e){
			model.setSub_code(ResultModel.SUB_CODE_SYSTEM_ERROR);
			model.setSub_msg(e.getMessage());
			logger.error("根据ID查询运输任务信息出错！id：" + id, e);
        }
        return model;
    }

    @ApiOperation(value = "新增运输任务信息")
    @RequestMapping(value = "/add", method = { RequestMethod.POST })
    public ResultModel addTaskAndOrder(@RequestBody TaskOrderDetailVO taskOrderDetailVO) {
    	ResultModel model = new ResultModel();
		try {
			taskService.insertTask(taskOrderDetailVO);
			model.setData(new JSONObject().fluentPut("result" , "添加成功"));
        } catch(BusinessException e){
        	model.setSub_code(1);
       	 	model.setData(new JSONObject().fluentPut("sub_msg" , e.getMessage()));
       	 	model.setSub_msg(e.getMessage());
        } catch (Exception e){
        	model.setSub_code(1);
        	model.setData(new JSONObject().fluentPut("sub_msg" ,  "添加失败"));
        	logger.error("新增运输任务时发生异常！", e);
        }
		return model;
    }

    @ApiOperation(value = "修改运输任务订单信息")
    @RequestMapping(value = "/update", method = { RequestMethod.POST })
    public ResultModel updateTask(@RequestBody TaskOrderDetailVO taskOrderDetailVO) {
    	ResultModel model = new ResultModel();
		try {
        	TTask data = taskService.getTaskById(taskOrderDetailVO.getId());
        	if(data ==null)throw new BusinessException("任务不存在，无法修改！");
        	
        	if(data.getExecutState() >0) throw new BusinessException("任务已执行，无法修改！");
        	
        	if(data.getConfirmState() == 0){
				taskService.updateTaskAndOrder(taskOrderDetailVO);//修改任务
	        	model.setData(new JSONObject().fluentPut("result" , "修改成功"));
			}else{//已确认的
				List<OrderVO> orderList = orderService.listOrderByTaskId(taskOrderDetailVO.getId());
				if(orderList.size() !=taskOrderDetailVO.getDetailList().size()) throw new BusinessException("任务已确认，无法增删订单！");
				
	        	TDriver tDriver = driverService.getDriverById(data.getDriverId());
	        	String title = "任务推送";
				String sub_title = "任务订单明细已更新，请查看!任务编号:"+taskOrderDetailVO.getTaskNo();
				TaskPushDTO dto = customOpenApiManager.greeAppTaskPush(title, sub_title, findTaskDetailUrl+data.getId(), tDriver.getPhone().trim(), "");
				if(dto !=null && dto.getList().length>0){
					taskService.updateTaskOrder(taskOrderDetailVO);// 修改任务的订单明细
		        	model.setData(new JSONObject().fluentPut("result" , "修改成功"));
				}else{
					model.setSub_code(1);
		       	 	model.setData(new JSONObject().fluentPut("sub_msg" ,  "司机号码不存在，修改失败！"));
				}
			}
        } catch(BusinessException e){
        	model.setSub_code(1);
       	 	model.setData(new JSONObject().fluentPut("sub_msg" , e.getMessage()));
       	 	model.setSub_msg(e.getMessage());
        } catch (Exception e){
			model.setSub_code(1);
       	 	model.setData(new JSONObject().fluentPut("sub_msg" ,  "修改失败"));
        	logger.error("修改运输任务订单信息发生异常！"+e);
        }
		return model;
    }

    @ApiOperation(value = "删除单个运输任务接口")
    @RequestMapping(value = "/delete/{id}", method = { RequestMethod.DELETE })
    @ApiImplicitParam(paramType = "path", name = "id", value = "运输任务ID", dataType = "Long", required = true)
    public ResultModel deleteTaskById(@PathVariable Long id) {
    	ResultModel model = new ResultModel();
    	try {
    		//删除任务记录
    		taskService.deleteTask(id);
    		model.setData(new JSONObject().fluentPut("result" , "删除成功"));
        } catch(BusinessException e){
        	model.setSub_code(1);
       	 	model.setData(new JSONObject().fluentPut("sub_msg" , e.getMessage()));
        } catch (Exception e){
        	model.setSub_code(1);
       	 	model.setData(new JSONObject().fluentPut("sub_msg" , "删除失败"));
       	 	model.setSub_msg(e.getMessage());
        	logger.error("根据ID删除信息出错！id：" + id, e);
        }
		return model;
    }
    
	@ApiOperation(value = "批量删除接口")
	@RequestMapping(value = "/deleteAll/{ids}", method = { RequestMethod.DELETE })
	@ApiImplicitParam(paramType = "path", name = "ids", value = "拼接需要删除的数据id串如：1,2,3,4，未确认则可以删除", dataType = "String", required = true)
	public ResultModel deleteAll(@PathVariable String ids) {
		ResultModel model = new ResultModel();
		try {
			if(StringUtils.isBlank(ids.trim())){
				throw new RuntimeException("数据不能为空，删除失败！");
			}
			// 目前的做法：含有一个以上已确认的任务，则全部无法删除
			String[] idArr = ids.trim().split(","); //不用
			//执行删除
			for (String string : idArr) {
				long id = Long.parseLong(string);
	        	//删除任务记录
	    		taskService.deleteTask(id);
			}
			model.setData(new JSONObject().fluentPut("result" , "删除成功"));
		} catch (BusinessException e){
            logger.info("批量删除失败：", e);
            model.setSub_code(1);
            model.setData(new JSONObject().fluentPut("sub_msg", "删除失败"));
            model.setSub_msg(e.getMessage());
        } catch (Exception e){
        	model.setSub_code(1);
        	model.setData(new JSONObject().fluentPut("sub_msg", "删除失败"));
            model.setSub_msg(e.getMessage());
            logger.error("批量删除任务异常！ids：" + ids, e);
        }
		return model;
	}
	
    @ApiOperation(value = "通过ID查询操作日记接口")
    @RequestMapping(value = "/getLogDataById", method = { RequestMethod.POST })
    public ResultModel getLogDataById(LogGirdQuery queryParam) {
		ResultModel model = new ResultModel();
		try {
			queryParam.setTableName(tableName);
            List<TLog> list = commonService.getLogDataById(queryParam);
            model.setData(new JSONObject().fluentPut("result", list));
            model.setPage(queryParam);
        }catch (Exception e){
        	model.setSub_code(ResultModel.SUB_CODE_SYSTEM_ERROR);
            model.setSub_msg(e.getMessage());
            logger.error("通过ID查询操作日记接口异常！", e);
        }
        return model;
    }
   
    @ApiOperation(value = "通过订单id或者订单号查询订单和订单明细接口（用于编辑的回显）",notes="数据格式：result:{订单信息,orderDetailList:[订单的物料信息]}")
    @RequestMapping(value = "/listOrderAndDetailByOrderIdOrOrderNo", method = { RequestMethod.POST })
    @ApiImplicitParams({
    	@ApiImplicitParam(paramType = "query", name = "orderId", value = "订单ID", dataType = "Long"),
    	@ApiImplicitParam(paramType = "query", name = "orderNo", value = "订单号", dataType = "String")
    })
    public ResultModel listOrderAndDetailByOrderIdOrOrderNo(Long orderId, String orderNo) {
        ResultModel model = new ResultModel();
        try {
        	// 订单信息
        	List<OrderVO> orderVOList = orderService.listOrderByOrderIdOrOrderNo(orderId, orderNo);
        	for (OrderVO orderVO2 : orderVOList) {
        		// 物料明细
        		List<OrderDetailVO> list = orderService.listOrderDetailByOrderIdOrOrderNo(orderVO2.getId(), null);
        		orderVO2.setOrderDetailList(list);
			}
            model.setData(new JSONObject().fluentPut("result", orderVOList));
        }catch (Exception e){
        	model.setSub_code(ResultModel.SUB_CODE_SYSTEM_ERROR);
            model.setSub_msg(e.getMessage());
            logger.error("通过订单id查询订单和订单明细接口！", e);
        }
        return model;
    }
    
    @ApiOperation(value = "确认所有未确认的任务",notes="不需要勾选，将所有未确认的任务执行为确认")
    @RequestMapping(value = "/updateStatus", method = { RequestMethod.POST })
    public ResultModel updateStatus() {
    	ResultModel model = new ResultModel();
    	StringBuffer listStr = new StringBuffer();
    	int successNum = 0;
    	//StringBuffer notfindStr = new StringBuffer();
        try {
        	// 任务确认
        	Map<String, Object> listPhone = taskService.getListTaskNoAndPhone();
        	String title = "任务推送";
        	String sub_title = "任务列表:";
        	if(listPhone!=null){
        		String taskNo = listPhone.get("taskNo").toString();
        		String phoneStr = listPhone.get("phone").toString();
        		String[] phoneStrs = phoneStr.split(",");
        		String[] taskNos = taskNo.split(",");
        		Date date = new Date();
        		if(phoneStrs.length >100){
        			String phoneStrings = "";
        			int a =1;
        			for (int i = 0; i < phoneStrs.length; i++) {
        				sub_title = sub_title+taskNos[i]+",";
        				phoneStrings = phoneStrings+phoneStrs[i]+",";
        				if(i >=99*a){
        					phoneStrings = phoneStrings.substring(0,phoneStrings.length()-1);
        					TaskPushDTO dto = customOpenApiManager.greeAppTaskPush(title, sub_title, findTaskIndexUrl, phoneStrings.trim(),"");
        					if(dto!=null){
                				String[] list = dto.getList();
                				if(list.length >0){
                					for (int j = 0; j < list.length; i++) {
        								String phone = list[j];//推送成功的电话号码
        								int num = taskService.updateNoConfirmStatusByPhone(phone, date);
        								successNum = successNum +num;
        								listStr.append(phone).append(",");
        							}
                				}
                			}
        					a++;
        					phoneStrings = "";
        					sub_title = "任务列表:";
						}
					}
        		}else{
        			sub_title = sub_title+taskNo;
        			TaskPushDTO dto = customOpenApiManager.greeAppTaskPush(title, sub_title, findTaskIndexUrl, phoneStr,"");
        			if(dto!=null){
        				String[] list = dto.getList();
        				//String[] notFind = dto.getNotFind();
        				if(list.length >0){
        					for (int i = 0; i < list.length; i++) {
								String phone = list[i];//推送成功的电话号码
								int num = taskService.updateNoConfirmStatusByPhone(phone, date);
								successNum = successNum +num;
								listStr.append(phone).append(",");
							}
        				}
        			}
        		}
        		String result = "";
        		if(listStr!=null){
        			result = listStr.toString() ;
        		}
        		result = result.substring(0, result.length()-1);
        		result = "成功确认共"+successNum+"条！已成功推送给如下司机手机号码:"+result;
        		model.setData(new JSONObject().fluentPut("result" , result));
        	}else{
        		model.setSub_code(0);
    			model.setData(new JSONObject().fluentPut("result" , "没有需要确认的任务！"));
        	}
        }catch (Exception e){
        	model.setSub_code(1);
            model.setData(new JSONObject().fluentPut("sub_msg" , "确认失败！"));
        	logger.error("任务确认接口异常", e);
        }
		return model;
    }
    
	
	@ApiOperation(value = "运输任务管理导出接口")
    @RequestMapping(value = "/exportTaskAndOrderGirdData", method = { RequestMethod.POST })
    public void exportTaskAndOrderGirdData(@RequestBody TaskGirdQuery queryParam, HttpServletRequest request, HttpServletResponse response) {
        try {
        	List<TaskListVO> list = taskService.listTaskAndOrderByPage(queryParam);
        	//List<Map<String, Object>> list = taskService.listTaskOrderExportByPage(queryParam);
            ExcelGenerateModel excelModel = new ExcelGenerateModel.Builder(list).cloumnList(queryParam.getCloums()).build();
            Workbook workbook = ExcelUtils.generateExcel(excelModel);
            this.sendWorkbook(workbook, "运输任务管理列表" , request, response);
        }catch (Exception e){
            logger.error("运输任务管理列表导出出错！", e);
        }
    }
    
    @ApiOperation(value = "备货指引管理导出接口")
    @RequestMapping(value = "/exportTaskAndOrderDetailGirdData", method = { RequestMethod.POST })
    public void exportTaskAndOrderDetailGirdData(@RequestBody TaskGirdQuery queryParam, HttpServletRequest request, HttpServletResponse response) {
        try {
            List<TaskStockVO> list = taskService.listTaskAndOrderDetailByPage(queryParam);
            //List<Map<String, Object>> list = taskService.exportTaskAndOrderDetailGirdData(queryParam);
            ExcelGenerateModel excelModel = new ExcelGenerateModel.Builder(list)
                    .cloumnList(queryParam.getCloums()).build();
            Workbook workbook = ExcelUtils.generateExcel(excelModel);
            this.sendWorkbook(workbook, "备货指引管理列表" , request, response);
        }catch (Exception e){
            logger.error("备货指引管理列表导出出错！", e);
        }
    }
    
    @ApiOperation(value = "根据任务ID查询任务明细详情(用于任务明细详情的数据回显)",notes="包含任务基本信息task，任务异常事件列表eventList，任务的物料订单明细列表orderList，任务节点列表nodeList，订单所含有的装货站点列表taskBranchList")
    @RequestMapping(value = "/getTaskDetailByTaskId/{taskId}", method = { RequestMethod.GET })
    @ApiImplicitParam(paramType = "path", name = "taskId", value = "运输任务ID", dataType = "Long", required = true)
    public ResultModel getTaskDetailByTaskId(@PathVariable Long taskId) {
    	ResultModel model = null;
		try {
			if(taskId == null || taskId <= 0){
                throw new RuntimeException("id不能为空或者少于等于0！");
            }
			// 1、任务对象
			TaskVO task = taskService.getTaskVOByTaskId(taskId);
			// 2、订单和订单对应的物料明细
			List<OrderVO> orderList = orderService.listOrderByTaskId(taskId);
        	for (OrderVO orderVO : orderList) {
        		// 物料明细
        		List<OrderDetailVO> list = orderService.listOrderDetailByOrderIdOrOrderNo(orderVO.getId(), null);
        		orderVO.setOrderDetailList(list);
			}
        	// 3、异常任务事件列表
        	List<TaskEventVO> eventList = taskEventService.getTaskEventList(taskId);
        	// 4、查询任务节点列表
        	List<TaskNodeVO> nodeList = taskNodeService.getTaskNodeList(taskId);
//        	for (TaskNodeVO taskNodeVO : nodeList) {
//				if(taskNodeVO.getNodeType() ==20 || taskNodeVO.getNodeType() ==21){
//					List<TaskMaterielVO> list = taskNodeService.getTaskMaterielListByNodeId(taskNodeVO.getId());
//					if(list.size() >0){
//						taskNodeVO.setGoods(list);
//					}
//				}
//			}
        	
        	// 5、订单所含有的站点列表
        	List<TaskBranchVO> branchList = taskService.getTaskBranchList(taskId);
        	TaskDetailVO taskDetail = new TaskDetailVO();
        	taskDetail.setTaskVO(task);
        	taskDetail.setOrderList(orderList);
        	taskDetail.setEventList(eventList);
        	taskDetail.setNodeList(nodeList);
        	taskDetail.setTaskBranchList(branchList);
        	model =  new ResultModel(0, 0, new JSONObject().fluentPut("result" , taskDetail));
        }catch (Exception e){
        	e.printStackTrace();
        	logger.error("根据任务ID查询任务明细详情！id：" + taskId, e);
        }
        return model;
    }
    
    @ApiOperation(value = "根据任务ID查询运输任务详情（打开编辑运输任务页面）")
    @RequestMapping(value = "/getTaskDetailByTaskIdToUpdate/{taskId}", method = { RequestMethod.GET })
    @ApiImplicitParam(paramType = "path", name = "taskId", value = "运输任务ID", dataType = "Long", required = true)
    public ResultModel getTaskDetailByTaskIdToUpdate(@PathVariable Long taskId){
    	ResultModel model = null;
    	try {
    		//查询所有未执行未生成的订单,并且根据taskId查询已关联的订单做个标识
    		TaskOrderDetailVO taskOrderDetailVO = taskService.selectAllOrderDetailAndSelectedOrder(taskId);
    		model = new ResultModel(0, 0, new JSONObject().fluentPut("result" , taskOrderDetailVO));
		} catch(BusinessException e){
        	model.setSub_code(1);
       	 	model.setData(new JSONObject().fluentPut("sub_msg" , e.getMessage()));
       	 	model.setSub_msg(e.getMessage());
        } catch (Exception e) {
			e.printStackTrace();
			logger.error("根据任务ID查询运输任务详情（打开编辑运输任务页面）发生异常！taskId：" + taskId, e);
		}
		return model;
    }
    
    @ApiOperation(value = "根据节点ID查询订单物料明细详情(装货点的物料订单明细)")
    @RequestMapping(value = "/getTaskMaterielVOListByNodeId/{nodeId}", method = { RequestMethod.GET })
    @ApiImplicitParam(paramType = "path", name = "nodeId", value = "任务节点ID", dataType = "Long", required = true)
    public ResultModel getTaskMaterielVOListByTaskId(@PathVariable Long nodeId) {
    	ResultModel model = null;
		try {
			if(nodeId == null || nodeId <= 0){
                throw new RuntimeException("id不能为空或者少于等于0！");
            }
			List<TaskMaterielVO> list = taskNodeService.getTaskMaterielListByNodeId(nodeId);
        	model =  new ResultModel(0, 0, new JSONObject().fluentPut("result" , list));
        }catch (Exception e){
        	e.printStackTrace();
        	logger.error("根据节点ID查询订单明细详情！id：" + nodeId, e);
        }
        return model;
    } 
    
    @ApiOperation(value = "通过任务id查询物料订单明细接口（用于货物明细查看）",notes="startPlaceName: 装货点,</br>"
    		+ "planNumber: 计划数量,</br>"
    		+ "actualNumber: 实际数量,</br>"
    		+ "orderNo: 订单号,</br>endPlaceName: 卸货点,</br>orderDate: 订单日期,</br>taskId: 任务id")
    @RequestMapping(value = "/listOrderDetailByTaskId/{taskId}", method = { RequestMethod.GET })
    @ApiImplicitParam(paramType = "path", name = "taskId", value = "任务ID", dataType = "Long", required = true)
    public ResultModel listOrderDetailByTaskId(@PathVariable Long taskId) {
        ResultModel model = new ResultModel();
        try {
        	List<Map<String, Object>> list = taskService.listOrderDetailByTaskId(taskId);
            model.setCode(0);
            model.setSub_code(0);
            model.setData(new JSONObject().fluentPut("result", list));
        }catch (Exception e){
        	model.setSub_code(1);
       	 	model.setData(new JSONObject().fluentPut("result", null));
            logger.error("通过任务id查询物料订单明细接口异常！", e);
        }
        return model;
    }
    
    @ApiOperation(value = "通过任务id分页查询物料明细，需要传任务id")
    @RequestMapping(value = "/listOrderDetailByPage", method = { RequestMethod.POST })
    public ResultModel listOrderDetailByPage(OrderDetailGirdQuery queryParam) {
        ResultModel model = new ResultModel();
        try {
        	List<Map<String, Object>> list = taskService.listOrderDetailByPage(queryParam);
            model.setCode(0);
            model.setSub_code(0);
            model.setData(new JSONObject().fluentPut("result", list));
            model.setPage(queryParam);
        }catch (Exception e){
        	model.setSub_code(1);
       	 	model.setData(new JSONObject().fluentPut("result", null));
            logger.error("通过任务id查询物料订单明细接口异常！", e);
        }
        return model;
    }
    
    @ApiOperation(value = "根据任务id和站点类型查询货物明细",notes="branchType=20表示装货站点，branchType=21表示卸货站点")
    @RequestMapping(value = "/getOrderDetailByTaskAndBranch", method = { RequestMethod.POST })
    @ApiImplicitParams({
    	@ApiImplicitParam(paramType = "query", name = "taskId", value = "任务ID", dataType = "Long"),
    	@ApiImplicitParam(paramType = "query", name = "branchType", value = "站点类型", dataType = "String")
    })
    public ResultModel getOrderDetailByTaskAndBranch(Long taskId, String branchType) {
    	ResultModel model = new ResultModel();
		try {
			if(taskId == null || taskId <= 0 || branchType ==null){
                throw new RuntimeException("输入值不能为空或者少于等于0！");
            }
			//有订单的站点列表
			List<TaskNodeVO> nodeList = taskNodeService.getOrderDetailByTaskAndBranch(taskId, branchType);
        	for (TaskNodeVO taskNodeVO : nodeList) {
        		String[] ids = taskNodeVO.getOrderIds().split(",");
        		// 查询订单列表    排序：拼板标识,最早送货时间，物料订单编号
				List<OrderVO> orderList = orderService.listOrderByOrderIds(ids);
				for (OrderVO orderVO : orderList) {
					List<OrderDetailVO> orderDetailList = orderService.listOrderDetailByOrderId(orderVO.getId());
					orderVO.setOrderDetailList(orderDetailList);
				}
        		taskNodeVO.setOrderList(orderList);
        	}
            model.setCode(0);
            model.setSub_code(0);
            model.setData(new JSONObject().fluentPut("result", nodeList));
        }catch (Exception e){
        	e.printStackTrace();
        	logger.error("根据任务id和站点类型查询货物明细出错", e);
        }
        return model;
    }
    
    @ApiOperation(value = "任务的车辆历史轨迹")
    @RequestMapping(value = "/getVehicleHistoryLocation/{taskId}", method = { RequestMethod.GET })
    @ApiImplicitParam(paramType = "path", name = "taskId", value = "任务id", dataType = "Long", required = true)
    public ResultModel getVehicleHistoryLocation(@PathVariable Long taskId) {
        ResultModel model = new ResultModel();
        List<VehicleHistoryDTO> result = new ArrayList<VehicleHistoryDTO>();
        try {
        	// 1、任务对象                 粤C05169 渝B19861 同T11111
        	TaskVO task = taskService.getTaskVOByTaskId(taskId);
        	if(task.getExecutState() ==1 || task.getExecutState() ==2){
        		String from = YYYYMMDDHHMMSS.format(task.getActualStartTime());
        		String to = YYYYMMDDHHMMSS.format(task.getExecutState() !=2 ? new Date() : task.getActualFinishTime());
        		result = openApiManager.getVehicleHistoryLocation(task.getVehicleNumber(), from, to);
        	}
        	model.setCode(0);
            model.setSub_code(0);
            model.setData(new JSONObject().fluentPut("result", result));
        }catch (Exception e){
        	model.setSub_code(1);
       	 	model.setData(new JSONObject().fluentPut("result", null));
            logger.error("任务的车辆历史轨迹接口异常！", e);
        }
        return model;
    }
    @ApiOperation(value = "根据任务ID查询当前任务节点")
    @RequestMapping(value = "/getTaskNodeListByTaskId/{taskId}", method = { RequestMethod.GET })
    @ApiImplicitParam(paramType = "path", name = "taskId", value = "运输任务ID", dataType = "Long", required = true)
    public ResultModel getTaskNodeListByTaskId(@PathVariable Long taskId, HttpServletRequest request) {
    	ResultModel model = new ResultModel();
		try {
        	TaskVO task = taskService.getTaskVOByTaskId(taskId);
        	// 2、查询任务节点列表
        	List<TaskNodeVO> nodeList = taskNodeService.getTaskNodeList(taskId);
        	/*
        	for (TaskNodeVO taskNodeVO : nodeList) {// 
				if(taskNodeVO.getNodeType() ==20 || taskNodeVO.getNodeType() ==21){
					List<TaskMaterielVO> list = taskNodeService.getTaskMaterielListByNodeId(taskNodeVO.getId());
					taskNodeVO.setGoods(list);
				}
			}*/
        	TaskDetailVO taskDetail = new TaskDetailVO();
        	taskDetail.setTaskVO(task);
        	taskDetail.setNodeList(nodeList);
        	model.setData(new JSONObject().fluentPut("result", taskDetail));
        }catch (Exception e){
        	model.setData(new JSONObject().fluentPut("sub_msg" , "查询异常"));
			model.setSub_code(ResultModel.SUB_CODE_SYSTEM_ERROR);
            model.setSub_msg(e.getMessage());
        	logger.error("根据任务ID查询当前任务节点！id：" + taskId, e);
        }
        return model;
    }
    
    
    @ApiOperation(value = "自动分配驾驶员")
    @RequestMapping(value = "/automaticallyDrivers", method = { RequestMethod.GET })
    public ResultModel automaticallyDrivers() {
    	ResultModel model = new ResultModel();
        try {
        	//获取还没有分配司机的任务
        	List<TTask> taskList = taskService.getNoDriverTask();
        	//得到成功分配司机的任务数
        	int successNum = taskService.automaticallyDrivers(taskList);
        	model.setData(new JSONObject().fluentPut("result" , "成功给"+successNum+"个任务分配司机,还有"+(taskList.size()-successNum)+"个任务未分配司机"));
        }catch (Exception e){
        	model.setSub_code(1);
            model.setData(new JSONObject().fluentPut("sub_msg" , "分配失败！"));
        	logger.error("自动分配驾驶员接口异常", e);
        }
		return model;
    }
    
    
    
    @ApiOperation(value = "推送的测试接口")
	@RequestMapping(value = "/testApi",  method = { RequestMethod.GET })
    public ResultModel ssss() {
		String title = "任务推送";
		String sub_title = "任务编号:T20180507001";
		String url = findTaskDetailUrl+2;
		String phones = "18924184049,18924184049,15889831311,15888888888";
		try {
			TaskPushDTO taskPush = customOpenApiManager.greeAppTaskPush(title, sub_title, url, phones, "");
			System.out.println(taskPush);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
    
	
}
